package com.rati.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rati.usercenter.common.BaseResponse;
import com.rati.usercenter.common.SelectType;
import com.rati.usercenter.exception.BusinessException;
import com.rati.usercenter.model.DTO.UserInfoDTO;
import com.rati.usercenter.model.VO.UserVO;
import com.rati.usercenter.model.domain.User;
import com.rati.usercenter.model.request.UserLoginRequest;
import com.rati.usercenter.model.request.UserRegisterRequest;
import com.rati.usercenter.service.UserService;
import com.rati.usercenter.utils.EnumUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.rati.usercenter.constant.UserConstant.*;
import static com.rati.usercenter.utils.ResultUtils.*;
import static com.rati.usercenter.common.ErrorCode.*;


/**
 * 用户接口
 *
 * @author Lwh
 * @time 2022/12/11 20:41
 */

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000"})
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, List<UserVO>> redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求对象
     * @return 注册成功的新用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(PARAMS_ERROR, "请求参数为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(PARAMS_ERROR, "请求参数含空");
        }

        long l = userService.userRegistry(userAccount, userPassword, checkPassword);
        return success(l);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求对象
     * @return 登录成功的用户对象信息
     */
    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(PARAMS_ERROR, "请求参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(PARAMS_ERROR, "请求参数含空");
        }

        UserVO user = userService.userLogin(userAccount, userPassword, request);
        return success(user);
    }

    /**
     * 根据用户名模糊查询用户（需要管理员权限）
     *
     * @param username 用户名
     * @return 模糊匹配的用户列表
     */
    @GetMapping("/search")
    public BaseResponse<List<UserVO>> searchUsers(@RequestParam String username, HttpServletRequest request) {
//        管理员鉴权
        if (userService.isNotAdmin(request)) {
            throw new BusinessException(NO_AUTH, "无管理员权限");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(username)) {
            wrapper.like("username", username);
        }
        List<User> userList = userService.list(wrapper);
        if (userList.isEmpty()) {
            throw new BusinessException(NULL_ERROR, "无符合要求的用户");
        }
//        用户脱敏
        List<UserVO> collect = userList.stream().map(
                user -> userService.getSafetyUser(user)
        ).collect(Collectors.toList());
        return success(collect);
    }

    /**
     * 根据id删除用户
     *
     * @param id 用户id
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestParam long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(PARAMS_ERROR, "非法请求参数");
        }
//        管理员鉴权
        if (userService.isNotAdmin(request)) {
            throw new BusinessException(NO_AUTH, "无管理员权限");
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(NULL_ERROR, "删除用户不存在");
        }
        boolean b = userService.removeById(id);
        return success(b);
    }

    /**
     * 获取当前登录用户的信息
     *
     * @return 当前登录用户的信息
     */
    @GetMapping("/get_current")
    public BaseResponse<UserVO> getCurrentUser(HttpServletRequest request) {
        return success(userService.getCurrentUser(request));
    }

    /**
     * 用户登出
     *
     * @return 登出标识
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        Integer i = userService.userLogout(request);
        return success(i);
    }

    /**
     * 根据标签查询用户
     *
     * @param tagNameList 用户需要含有的标签
     * @param flag        查询策略 1-部分匹配 2-全部匹配
     * @return 符合条件的用户列表
     */
    @GetMapping("/searchByTags")
    public BaseResponse<List<UserVO>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList, int flag, HttpServletRequest request) {
        if (tagNameList.isEmpty()) {
            throw new BusinessException(PARAMS_ERROR, "传入参数为空");
        }
        User self = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (self == null) {
            throw new BusinessException(NO_LOGIN, "用户未登录");
        }
        List<UserVO> users = userService.searchByTags(tagNameList, EnumUtils.ToEnum(SelectType.class, "num", flag));
//        过滤掉查询者自己
        List<UserVO> collect = users.stream().filter(user -> !Objects.equals(user.getId(), self.getId())).collect(Collectors.toList());
        if (collect.isEmpty()) {
            throw new BusinessException(NULL_ERROR, "未查询到符合条件的用户");
        }
        return success(collect);
    }

    /**
     * 普通用户更新自己的用户信息
     *
     * @param user 新用户信息
     * @return 更新结果
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserInfoDTO user, HttpServletRequest request) {
//        判空
        if (user == null) {
            throw new BusinessException(PARAMS_ERROR, "传入参数为空");
        }
//        鉴权、修改(service)
        UserVO loginUser = userService.getCurrentUser(request);
        int result = userService.updateUser(user, loginUser);
        if (result == 0) {
            throw new BusinessException(NULL_ERROR, "无匹配用户");
        }
        return success(result);
    }

    /**
     * 分页查询用户
     *
     * @param pageSize size
     * @param pageNum  current
     * @return 用户列表
     */
    @GetMapping("/list/page")
    public BaseResponse<List<UserVO>> listUsersByPage(long pageSize, long pageNum, HttpServletRequest request) {
        UserVO currentUser = userService.getCurrentUser(request);
        ValueOperations<String, List<UserVO>> valueOperations = redisTemplate.opsForValue();
        String redisKey = String.format("usercenter:user:recommend:%s", currentUser.getId());
//        先查缓存
        List<UserVO> list = valueOperations.get(redisKey);
        if (list != null) {
            return success(list);
        }
//        无缓存
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), wrapper);
        list = page.getRecords().stream().map(userService::getSafetyUser).collect(Collectors.toList());
//        写缓存
        try {
            valueOperations.set(redisKey, list, 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis set key error: " + e);
        }
        return success(list);
    }

    /**
     * 查询匹配用户
     *
     * @param num 目标查询数量
     * @return 用户列表
     */
    @GetMapping("/list/recommend")
    public BaseResponse<List<UserVO>> listUsersByRecommend(int num, HttpServletRequest request) {
        if (num < 1) {
            throw new BusinessException(PARAMS_ERROR, "请求参数非法");
        }
        UserVO currentUser = userService.getCurrentUser(request);
        List<UserVO> matchUsers = userService.getMatchUsers(num, currentUser);
        if (matchUsers.isEmpty()) {
            throw new BusinessException(NULL_ERROR, "未查询到匹配用户");
        }
        return success(matchUsers);
    }

}
